<script setup>
import Cookies from 'js-cookie'
import { onMounted, ref ,reactive} from 'vue';
import { defineProps } from 'vue';
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import {loginAPI} from '@/apis/user'
import {registAPI} from '@/apis/user'
import {useRouter} from 'vue-router'
import { getIdentifyAPI} from '@/apis/user'
import {uppsdAPI} from '@/apis/user'


// 表单绑定ref

const sms = reactive({
   disabled:false,
   total:60,
   count:0
  })
const form = ref({
  email: '',
  password: '',
  agree:true,
  rname:'',
  remail:'',
  rpassword:'',
  ragree:true,
  rconfirm:'',
  code:'',
  upemail:'',
  uppassword:'',
  upconfirm:''
  
});
console.log(form.value.upemail)
// 默认选中
const activeTab = ref('login')
const router = useRouter()
// 给登录form制定规则
const rules = ref({
  email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  agree: [
    {
      validator: (rule, val, callback) => {
        return val ? callback() : new Error('请先同意协议')
      }
    }
  ]
});
// 登录的动作 先表单验证 然后再请求接口
const formRef = ref(null);
const submitForm = () => {
  const {email,password} = form.value
  formRef.value.validate(async (valid) => {
    if (valid) {
      let response = await loginAPI({ email, password })
      console.log(response);
      if(response.success==true) {
         Cookies.set('token', response.data, { expires: 1 });
         ElMessage({ type: "success", message: response.message });
         router.push({ path: '/' })
      }else{
        ElMessage({type:'warning',message:response.message});
      }
    } else {
      console.log('error submit!!');
      return false;
    }
  });
};

// 给注册form制定规则
const rrules = ref({
  rname:[{ required: true, message: '请输入用户名', trigger: 'blur' }],
  remail: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
  rpassword: [{ required: true, message: '请输入密码', trigger: 'blur' },
  { max:14,min:6, message: '密码长度为6-14', trigger: 'blur' }],
  rconfirm: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== form.value.rpassword) {
              callback(new Error('两次密码输入不一致'));
            } else {
              callback();
            }
          },
          trigger: 'blur'
        }
      ],
  ragree: [
    {
      validator: (rule, val, callback) => {
        return val ? callback() : new Error('请先同意协议')
      }
    }
  ]
});

const rformRef = ref(null);
async function getIdentifyCode(email, form) {
  // 提交表单验证
  const valid = await form.validate()

  if (valid) {
    try {
      // 发送验证码操作
      
      await getIdentifyAPI({email});
      ElMessage({ type: 'success', message: '验证码发送成功' });

      // 启用计时器
      sms.count = sms.total
      sms.disabled = true
      let timer = setInterval(() => {
        if (sms.count > 1 && sms.count <= sms.total) {
          sms.count--
        } else {
          sms.disabled = false
          clearInterval(timer)
        }
      }, 1000)
    } catch (error) {
      console.error(error);
      ElMessage({ type: 'error', message: '验证码发送失败' });
    }
  } else {
    // 表单验证不通过，提示错误信息
    ElMessage({ type: 'warning', message: '请正确填写信息后再操作' });
  }
}

// 注册的动作 先表单验证 然后再请求接口

const submitReForm = () => {
const {rname,remail,rpassword,code} = form.value

  rformRef.value.validate(async (valid) => {
    console.log(rname,remail,rpassword,code)

    if (valid) {
      let response = await registAPI({ rname,remail,rpassword,code})
      console.log(response);
      if(response.success==true) {
        ElMessage({ type: "success", message: '注册成功' });
        //router.replace({ path: '/' })
        location.reload();
      }else{
        ElMessage({type:'warning',message:response.message});
      }
    } else {
      console.log('error submit!!');
      return false;
    }
  });
};


const dialogTableVisible = ref(false)
const dialogFormVisible = ref(false)
// 忘记密码的验证规则
const uprules = ref({
  upemail: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],

  uppassword: [{ required: true, message: '请输入密码', trigger: 'blur' },
  { max:14,min:6, message: '密码长度为6-14', trigger: 'blur' }],
  upconfirm: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value != form.value.uppassword) {
              callback(new Error('两次密码输入不一致'));
            } else {
              callback();
            }
          },
          trigger: 'blur'
        }
      ],
  
});

const upformRef = ref(null);
const UpdatePsd = () => {
const {upemail,uppassword,code} = form.value
let email = upemail 
let password = uppassword
  upformRef.value.validate(async (valid) => {
    if (valid) {
      let response = await uppsdAPI({email,password,code})
      if(response.success==true) {
        ElMessage({ type: "success", message: '修改成功' });
        //router.replace({ path: '/login' })
        location.reload();
      }else{
        ElMessage({type:'warning',message:response.message});
      }
    } else {
      console.log('error submit!!');
      return false;
    }
  });
};

</script>

<template>
  <div class="login">
    <div class="left">
      <img src="../../assets/img/11.png"/>
    </div>
    <div class="right">
    <section class="login-section">
      <div class="wrapper">
        <div class="login-box ">
          <div class="form">
            <el-tabs v-model="activeTab" class="demo-tabs ">
              <el-tab-pane  class="tab" label="登录" name="login">
            <el-form
              ref="formRef"
              :model="form"
              :rules="rules"
              label-position="right"
              label-width="65px"
              status-icon
              class="el_form"
              hide-required-asterisk="false"
            >
              <el-form-item prop="email" label="邮箱">
                <el-input v-model="form.email" />
              </el-form-item>
              <el-form-item prop="password" label="密码">
                <el-input v-model="form.password" type="password" />
              </el-form-item>
              <el-form-item prop="agree" label-width="22px">
                <el-checkbox v-model="form.agree" size="large">
                  我已同意隐私条款和服务条款
                </el-checkbox>
              </el-form-item>
              <el-button size="large" class="subBtn" @click="submitForm">
                点击登录
              </el-button>
              <el-button text @click="dialogFormVisible = true">
                忘记密码
              </el-button>
              <el-dialog v-model="dialogFormVisible" title="修改密码">
              <el-form
              ref="upformRef"
              :model="form"
              :rules="uprules"
              label-position="right"
              label-width="100px"
              status-icon
              class="el_form"
               hide-required-asterisk="false"
            >
              <el-form-item prop="upemail" label="邮箱" >
                <el-input v-model="form.upemail" />
              </el-form-item>
              <el-form-item prop="uppassword" label="新密码" >
                <el-input v-model="form.uppassword" type="text" />
              </el-form-item>
              <el-form-item prop="upconfirm"  label="确认密码" >
                <el-input v-model="form.upconfirm" type="text" />
              </el-form-item>
               <el-form-item prop="code" label="验证码">
              <el-input
                type="text"
                v-model="form.code"
                class="inpWidth"
              />
              <el-button v-if="!sms.disabled" type="primary"  @click="getIdentifyCode(form.upemail,upformRef)">
                 发送验证码
              </el-button>
              <el-button v-else type="primary" style="color:black" disabled >
                 {{ sms.count }} 秒后重新发送
              </el-button>
         
          </el-form-item> 
              <el-button size="large" class="subBtn" @click="UpdatePsd">
                确认修改
              </el-button>
             
            </el-form>
                
          </el-dialog>
             
            </el-form>
             </el-tab-pane>
             <el-tab-pane class="tab" label="注册" name="register">
              <el-form
              ref="rformRef"
              :model="form"
              :rules="rrules"
              label-position="right"
              label-width="83px"
              status-icon
              class="el_form"
               hide-required-asterisk="false"
              

            >
            <el-form-item prop="rname" label="用户名">
                <el-input v-model="form.rname" />
              </el-form-item>
              <el-form-item prop="remail" label="邮箱">
                <el-input v-model="form.remail" />
              </el-form-item>
              <el-form-item prop="rpassword" label="密码">
                <el-input v-model="form.rpassword" type="password" />
              </el-form-item>
              <el-form-item prop="rconfirm"  label="确认密码">
                <el-input v-model="form.rconfirm" type="password" />
              </el-form-item>
               <el-form-item prop="code" label="验证码">
            <el-row>
              <el-input
                type="text"
                v-model="form.code"
                class="inpWidth"
              />
              <el-button v-if="!sms.disabled" type="primary"  @click="getIdentifyCode(form.remail,rformRef)">
                 发送验证码
              </el-button>
              <el-button v-else type="primary" style="color:black" disabled >
                 {{ sms.count }} 秒后重新发送
              </el-button>
            </el-row>
          </el-form-item>
              <el-form-item  prop="ragree" label-width="20px">
                <el-checkbox v-model="form.ragree" size="large">
                  我已同意隐私条款和服务条款
                </el-checkbox>
              </el-form-item>
              <el-button size="large" class="subrBtn" @click="submitReForm">
                点击注册
              </el-button>
             
            </el-form>
              </el-tab-pane>
              </el-tabs>
          </div>
        </div>
      </div>
    </section>
    </div>
  </div>
</template>



<style scoped>

.login {
  width: 100%;
  height: 100vh;
  display: flex;
  align-items: center;

}
.left{
  width: 60%;
  height: 100vh;
}
.left img{
  width: 100%;
  height: 100vh;
}
.right{
  width: 40%;
}
.login-section {
  width: 450px;
  height: 500px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 4px 4px 20px #ccc;
  background: linear-gradient(to bottom, rgba(255, 255, 255, 0.9), rgba(255, 255, 255, 0.7));
}

.wrapper {
  margin: 5% 10% 10% 6%;
}
 
.demo-tabs  {
  padding: 30px 12px 0;
  font-size: 25px!important;
  font-weight: 700!important;
}

.el_form{
  margin: 10px 2% 10% -4% ;
}

.subBtn{
  margin-left: 18%;
}
.subrBtn{
  margin-left: 22%;
  margin-top: -8%;
}

.inpWidth{
  margin-bottom: 8px;
} 





</style>